﻿using AutoMapper;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ShenNius.Cms.API.Domain.Entity;
using ShenNius.Cms.API.Dtos.Input;
using ShenNius.Cms.API.Dtos.Output;
using ShenNius.FileManagement;
using ShenNius.Repository;
using ShenNius.Repository.Extensions;
using ShenNius.Sys.API.Controllers;
using ShenNius.Sys.API.Domain.Entity;
using ShenNius.Sys.API.Dtos.Common;
using ShenNius.Sys.API.Infrastructure.Configs;
using SqlSugar;
using System;
using System.Threading.Tasks;

/*************************************
* 类名：ArticleController
* 作者：realyrare
* 邮箱：mahonggang8888@126.com
* 时间：2021/3/11 17:23:48
*┌───────────────────────────────────┐　    
*│　   版权所有：神牛软件　　　　	     │
*└───────────────────────────────────┘
**************************************/

namespace ShenNius.Cms.API.Controllers
{
    [Route("api/cms/[controller]/[action]")]
    public class ArticleController : ApiTenantBaseController<Article, DetailTenantQuery, DeletesTenantInput, KeyListTenantQuery, ArticleInput, ArticleModifyInput>
    {
        private readonly IBaseRepository<Article> _repository;
        private readonly IUploadFile _uploadHelper;
        private readonly ISqlSugarClient _db;
        public ArticleController(IBaseRepository<Article> repository, IMapper mapper, IUploadFile uploadHelper, ISqlSugarClient db) : base(repository, mapper)
        {
            _repository = repository;
            _uploadHelper = uploadHelper;
            _db = db;
        }
        [HttpGet]
        public override async Task<ApiResult> GetListPages([FromQuery] KeyListTenantQuery query)
        {
            var res = await _db.Queryable<Article, Column>((a, c) => new JoinQueryInfos(JoinType.Inner, a.ColumnId == c.Id && a.IsDeleted == false && c.IsDeleted == false))
                 .WhereIF(query.TenantId != 0, (a, c) => a.TenantId == query.TenantId && c.TenantId == query.TenantId)
                .WhereIF(!string.IsNullOrEmpty(query.Key), (a, c) => a.Title.Contains(query.Key))
                   .OrderBy((a, c) => a.Id, OrderByType.Desc)
                   .Select((a, c) => new
                   {
                       Title = a.Title,
                       CreateTime = a.CreateTime,
                       ModifyTime = a.ModifyTime,
                       Id = a.Id,
                       Audit = a.Audit,
                       IsTop=a.IsTop,
                       IsComment = a.IsComment,
                       IsHot = a.IsHot,
                       Author = a.Author,
                       Source = a.Source,
                       ColumnName = c.Title,
                       TenantName = SqlFunc.Subqueryable<Tenant>().Where(s => s.Id == query.TenantId).Select(s => s.Name),
                   })
                   .ToPageAsync(query.Page, query.Limit);
            return new ApiResult(data: new { count = res.TotalItems, items = res.Items });
        }
        [HttpPost]
        public async Task<ApiResult> ChangeState([FromBody] ArticleStateChangeInput input)
        {
         var model= await  _repository.GetModelAsync(d => !d.IsDeleted && d.Id == input.Id && d.TenantId == input.TenantId);
            if (model==null||model.Id<=0)
            {
                return new ApiResult("该条数据已不存在！");
            }
            model.ChangeState(input.Type, input.StateValue);
           var res= await _repository.UpdateAsync(model, d => new { d.CreateTime });
            return res>0?  ApiResult.Successed("状态更改成功"): new ApiResult("状态更改失败");
        }

        [HttpPost, AllowAnonymous]
        public IActionResult QiniuFile()
        {
            var files = Request.Form.Files[0];
            var data = _uploadHelper.Upload(files, "article/");
            //TinyMCE 指定的返回格式
            return Ok(new { location = data });
        }
        [HttpGet]
        public async Task<IActionResult> Export()
        {
            IExporter exporter = new ExcelExporter();
            var datas = await _db.Queryable<Article>().Where(d => !d.IsDeleted)
                   .OrderBy(a => a.Id, OrderByType.Desc)
                   .Select(a => new ArticleOutput
                   {
                       Title = a.Title,
                       CreateTime = a.CreateTime,
                       ModifyTime = a.ModifyTime,
                       Audit = a.Audit,
                       Author = a.Author,
                       Source = a.Source,
                       ColumnName = SqlFunc.Subqueryable<Column>().Where(s => s.Id == a.ColumnId).Select(s => s.Title),
                   }).ToListAsync();

            if (datas.Count <= 0)
            {
                throw new ArgumentNullException("关键词列表没有可用数据导出！");
            }
            var result = await exporter.Export($"{nameof(Article)}.xlsx", datas);
            return File(System.IO.File.ReadAllBytes(result.FileName), "application/vnd.ms-excel", $"{nameof(Keyword)}.xlsx");
        }
    }
}